<template>
  <div class="employee-management">
    <el-card shadow="hover">
      <div class="card-header">
        <h2>人员管理</h2>
        <el-button type="primary" @click="showAddDialog">添加人员</el-button>
      </div>

      <el-table :data="employees" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="type" label="类型">
          <template #default="{ row }">{{ formatType(row.type) }}</template>
        </el-table-column>
        <el-table-column prop="serial_number" label="序号"></el-table-column>
        <el-table-column prop="feishu_user_id" label="飞书用户ID"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteEmployee(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑人员对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入人员姓名"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择人员类型">
            <el-option label="内勤" :value="1"></el-option>
            <el-option label="外勤" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="序号" prop="serial_number">
          <el-input v-model.number="form.serial_number" placeholder="请输入排序序号"></el-input>
        </el-form-item>
        <el-form-item label="飞书用户ID" prop="feishu_user_id">
          <el-input v-model="form.feishu_user_id" placeholder="请输入飞书用户ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '../services/api';

// 状态变量
const employees = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('添加人员');
const formRef = ref(null);
const form = ref({
  name: '',
    type: 1,
    serial_number: 1,
    feishu_user_id: ''
});
const rules = ref({
  name: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
  type: [{ required: true, message: '请选择人员类型', trigger: 'blur' }],
  serial_number: [{ required: true, message: '请输入排序序号', trigger: 'blur' }]
});
const currentId = ref(null);

// 格式化类型显示
const formatType = (typeValue) => {
  const types = {
    1: '内勤',
    2: '外勤'
  };
  return types[typeValue] || '未知';
};

// 计算指定类型的最大序号
const getMaxSerialNumber = (type) => {
  const filteredEmployees = employees.value.filter(emp => emp.type === type);
  if (filteredEmployees.length === 0) return 0;
  return Math.max(...filteredEmployees.map(emp => emp.serial_number));
};

// API请求
const fetchEmployees = async () => {
  try {
    const response = await api.employees.getAll();
    // 按类型和序号排序
    employees.value = response.sort((a, b) => {
      if (a.type !== b.type) {
        return a.type - b.type;
      }
      return a.serial_number - b.serial_number;
    });
  } catch (error) {
    ElMessage.error('获取人员列表失败: ' + (error.response?.data?.error || error.message));
  }
};

const addEmployee = async () => {
  try {
    await api.employees.create(form.value);
    ElMessage.success('人员添加成功');
    dialogVisible.value = false;
    fetchEmployees();
  } catch (error) {
    ElMessage.error('添加人员失败: ' + (error.response?.data?.error || error.message));
  }
};

const updateEmployee = async () => {
  try {
    await api.employees.update(currentId.value, form.value);
    ElMessage.success('人员更新成功');
    dialogVisible.value = false;
    fetchEmployees();
  } catch (error) {
    ElMessage.error('更新人员失败: ' + (error.response?.data?.error || error.message));
  }
};

const deleteEmployee = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该人员吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    await api.employees.delete(id);
    ElMessage.success('人员删除成功');
    fetchEmployees();
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('删除人员失败: ' + (error.response?.data?.error || error.message));
    }
  }
};

// 表单提交
const submitForm = async () => {
  await formRef.value.validate();
  if (currentId.value) {
    await updateEmployee();
  } else {
    await addEmployee();
  }
};

// 显示添加对话框
const showAddDialog = () => {
  currentId.value = null;
  dialogTitle.value = '添加人员';
  const defaultType = 1;
  const maxSerialNumber = getMaxSerialNumber(defaultType);
  form.value = {
    name: '',
    type: defaultType,
    serial_number: maxSerialNumber + 1,
    feishu_user_id: ''
  };
  // 监听类型变化，动态更新序号
  watch(() => form.value.type, (newType) => {
    const maxSerial = getMaxSerialNumber(newType);
    form.value.serial_number = maxSerial + 1;
  });
  dialogVisible.value = true;
};

// 显示编辑对话框
const showEditDialog = (row) => {
  currentId.value = row.id;
  dialogTitle.value = '编辑人员';
  form.value = {
    name: row.name,
    type: row.type,
    serial_number: row.serial_number,
    feishu_user_id: row.feishu_user_id || ''
  };
  dialogVisible.value = true;
};

// 页面加载时获取数据
onMounted(() => {
  fetchEmployees();
});
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>